package cn.yunyichina.provider.bed.thread;

import cn.yunyichina.provider.bed.dao.InpatientRecordDao;
import cn.yunyichina.provider.bed.dao.InpatientRecordListDao;
import cn.yunyichina.provider.bed.entity.InpatientRecord;
import cn.yunyichina.provider.bed.entity.InpatientRecordList;
import cn.yunyichina.provider.bed.vo.BedVo;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.base.MedicalCardVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.bed.BedRecordsVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by 15-AK on 2016/12/15.
 */
public class InpatientRecordRunnable  implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(InpatientRecordRunnable.class);
    List<BedRecordsVoResponse> bedRecordsVoResponseList;
    private BedVo requestVo;

    public InpatientRecordRunnable(List<BedRecordsVoResponse> bedRecordsVoResponseList,BedVo requestVo) {
        this.bedRecordsVoResponseList = bedRecordsVoResponseList;
        this.requestVo = requestVo;
    }

    @Override
    public void run() {

       logger.info("保存住院记录开始======bedRecordsVoResponseList ="+JsonUtils.toJsonString(bedRecordsVoResponseList));
        InpatientRecordDao inpatientRecordDao = SpringContextHandler.getBean(InpatientRecordDao.class);
        //存住院记录基本信息
        BedRecordsVoResponse bedRecord = bedRecordsVoResponseList.get(0);
        InpatientRecord inpatientRecord = inpatientRecordDao.selectByAdmissionNoAndOrgCode(bedRecord.getAdmissionNo(),requestVo.getHospitalCode());

        //查询绑定卡
        MedicalCardVo medicalCard = null;
        if (StringUtils.isNotBlank(requestVo.getPatCardNo())&&StringUtils.isNotBlank(requestVo.getPatCardType())){
            logger.info("【出院带药保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get request=");
            medicalCard =  BaseService.getMedicalCardByCardNo(requestVo.getHospitalCode(),requestVo.getPatCardNo(),requestVo.getPatCardType(),requestVo.getAppId(),null);
            //Response medicalResponse = BaseService.callHumpFromInternal("yyt.base.medicalcard.by.id.get", JsonUtils.toJsonString(medicalParam));
            if (medicalCard == null) {
                throw new CallException("14010","找不到绑定卡信息 card_no=" +requestVo.getPatCardNo());
            }
        }

        //MedicalCard medicalCard = JsonUtils.parseObject(medicalResponse.getResult(), MedicalCard.class);


        // 查询组织信息-----------------------------------------------start
        Map<String, String> orgParamMap = new HashMap<String, String>();
        orgParamMap.put("org_code", requestVo.getHospitalCode());
        logger.info("【住院记录-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgParamMap));
        Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgParamMap));
        logger.info("【住院记录-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
        if (!"0".equals(orgResponse.getResultCode())) {
            throw new CallException("14010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        List<Org> orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
        if (org.springframework.util.CollectionUtils.isEmpty(orgList)) {
            throw new CallException("14010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        Org org = orgList.get(0);

        if (inpatientRecord == null) {
            logger.info("新增住院记录");
            inpatientRecord = new InpatientRecord();
            inpatientRecord.setId(PKGenerator.generateId());
            inpatientRecord.setAdmissionNo(bedRecord.getAdmissionNo());
            inpatientRecord.setBranchCode(requestVo.getHospitalCode());
            inpatientRecord.setPatCardNo(requestVo.getPatCardNo());
            if (null != requestVo.getPatCardType()){
                inpatientRecord.setPatCardType(Short.valueOf(requestVo.getPatCardType()));
            }
            inpatientRecord.setPatId(medicalCard==null?"":medicalCard.getPatId());
            inpatientRecord.setPatName(medicalCard==null?"":medicalCard.getPatName());
            inpatientRecord.setOrgId(org.getId());
            inpatientRecord.setOrgCode(requestVo.getHospitalCode());
            inpatientRecord.setOrgName(org.getOrgName());
            inpatientRecord.setBranchId("");
            inpatientRecord.setBranchName("");
            inpatientRecord.setBranchCode("");
            inpatientRecord.setCreatedTime(DateUtils.dateToString(new Date()));

            inpatientRecordDao.insert(inpatientRecord);
            logger.info("住院记录新增结束");
        }

        InpatientRecordListDao inpatientRecordListDao = SpringContextHandler.getBean(InpatientRecordListDao.class);

        //存住院记录明细
        List<InpatientRecordList>inpatientRecordLists =  inpatientRecordListDao.selectByInpatientRecordId(inpatientRecord.getId());
        List<InpatientRecordList>inpatientRecordListToSave = new ArrayList<>();
        Map<String ,InpatientRecordList> inPatientIdMap = new HashMap<>();

        if (CollectionUtils.isNotEmpty(inpatientRecordLists)){
            logger.info("db inpatientRecordLists==="+ JsonUtils.toJsonString(inpatientRecordLists));
            //不为空就判断还有哪些是没有入库的
            for (InpatientRecordList inpatientRecordList :inpatientRecordLists){
                inPatientIdMap.put(inpatientRecordList.getInpatientId(),inpatientRecordList);
            }
            for (BedRecordsVoResponse vo : bedRecordsVoResponseList){
                if(inPatientIdMap.get(vo.getPatientId())==null){
                    //还住院记录还没有保存在数据库中，需要保存
                    inpatientRecordListToSave.add(buildInpatientRecordList(vo,inpatientRecord.getId()));
                }
            }
        }else{
            //为空直接插入
            logger.info("直接插入住院记录");
            for (BedRecordsVoResponse vo : bedRecordsVoResponseList){
                inpatientRecordListToSave.add(buildInpatientRecordList(vo,inpatientRecord.getId()));
            }
        }

        if (CollectionUtils.isNotEmpty(inpatientRecordListToSave)){
            logger.info("要新增的住院记录明细=="+JsonUtils.toJsonString(inpatientRecordListToSave));
            inpatientRecordListDao.batchInsert(inpatientRecordListToSave);
        }

    }
    private InpatientRecordList buildInpatientRecordList(BedRecordsVoResponse vo,String nPatientRecordId){
        InpatientRecordList inpatientRecordItem = new InpatientRecordList();
        //主表记录id 作为外键
        inpatientRecordItem.setNpatientRecordId(nPatientRecordId);
        inpatientRecordItem.setId(PKGenerator.generateId());
        inpatientRecordItem.setInpatientId(vo.getPatientId());
        inpatientRecordItem.setAdmissionNo(vo.getAdmissionNo());
        inpatientRecordItem.setBedNo(vo.getBedNo());
        inpatientRecordItem.setInDate(vo.getInDate());
        inpatientRecordItem.setBeginInDate(vo.getInDate());
        inpatientRecordItem.setBeginOutDate(vo.getOutDate());
        inpatientRecordItem.setDeptName(vo.getDeptName());
        inpatientRecordItem.setStatus(Short.parseShort(vo.getStatus()));
        inpatientRecordItem.setOtherDesc(vo.getOtherDesc());
        inpatientRecordItem.setDoctorCode(vo.getDoctorCode());
        inpatientRecordItem.setDoctorName(vo.getDoctorName());
        inpatientRecordItem.setInTime(Integer.parseInt(vo.getInTime()));
        inpatientRecordItem.setTotalFee(Integer.parseInt(vo.getTotalFee()));
        return inpatientRecordItem;

    }




}
